<?php

namespace app\common\model\xilumarket;

use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_except;
use function fast\array_get;


class OrderComment extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xilumarket_order_comment';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        //'createtime_text'
    ];

    public static function addComment($params) {
        $order_id = array_get($params,'order_id');
        if(!$order_id){
            throw new Exception("参数错误");
        }
        $order = Order::get($order_id);
        if(!$order || $order->state != 3){
            throw new Exception("不允许评论");
        }
        if($order->comment_status == 1){
            throw new Exception("不要重复评论");
        }
        try {
            $images = array_get($params,'images');
            $params['images'] = $images? (is_array($images) ? implode(',',$images) : $images) :'';
            $params['content'] = array_get($params,'content', '');
            check_sens_word($params['content']);
            $params['status'] = 'normal';
            $comment = new self();
            $ret = $comment->allowField(true)->save($params);
            if ($ret === false) {
                throw new Exception($comment->getError());
            }
            $order->comment_status = 1;
            $order->commenttime = time();
            $order->order_status = 3; //已完成
            $order->allowField(['comment_status','commenttime','order_status'])->save();
            return $comment;
        }catch (Exception $e) {
            throw $e;
        }
    }
}
